/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2019-2021. All rights reserved.
 */

#include "plugins/ecmascript/runtime/accessor_data.h"
#include "plugins/ecmascript/runtime/base/builtins_base.h"
#include "plugins/ecmascript/runtime/base/object_helper.h"
#include "plugins/ecmascript/runtime/internal_call_params.h"
#include "plugins/ecmascript/runtime/js_function.h"
#include "plugins/ecmascript/runtime/js_iterator.h"

namespace ark::ecmascript::base {
// ES2021 20.1.2.7.1
JSTaggedValue ObjectHelper::CreateDataPropertyOnObject(EcmaRuntimeCallInfo *argv)
{
    ASSERT(argv);
    JSThread *thread = argv->GetThread();

    // 1. Let O be the this value.
    JSHandle<JSTaggedValue> object = builtins_common::GetThis(argv);

    // 2. Assert: Type(O) is Object.
    ASSERT(object->IsObject());

    // 3. Assert: O is an extensible ordinary object.
    ASSERT(object->IsExtensible(thread));

    // 4. Let propertyKey be ? ToPropertyKey(key).
    JSHandle<JSTaggedValue> key = builtins_common::GetCallArg(argv, 0);
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> propertyKey = JSTaggedValue::ToPropertyKey(thread, key);
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // 5. Perform ! CreateDataPropertyOrThrow(O, propertyKey, value).
    JSHandle<JSTaggedValue> value = builtins_common::GetCallArg(argv, 1);
    JSObject::CreateDataPropertyOrThrow(thread, JSTaggedValue::ToObject(thread, object), propertyKey, value);
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);

    // 6. Return undefined.
    return JSTaggedValue::Undefined();
}

JSTaggedValue ObjectHelper::AddEntriesFromIterable(JSThread *thread, const JSHandle<JSTaggedValue> &target,
                                                   const JSHandle<JSTaggedValue> &iterable,
                                                   JSHandle<JSTaggedValue> &adder)
{
    // If IsCallable(adder) is false, throw a TypeError exception
    if (!adder->IsCallable()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "adder is not callable", adder.GetTaggedValue());
    }
    // Let iter be GetIterator(iterable).
    JSHandle<JSTaggedValue> iter(JSIterator::GetIterator(thread, iterable));
    // ReturnIfAbrupt(iter).
    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, iter.GetTaggedValue());
    JSHandle<JSTaggedValue> keyIndex(thread, JSTaggedValue(0));
    JSHandle<JSTaggedValue> valueIndex(thread, JSTaggedValue(1));
    JSHandle<JSTaggedValue> next = JSIterator::IteratorStep(thread, iter);
    JSMutableHandle<JSTaggedValue> status(thread, JSTaggedValue::Undefined());
    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, next.GetTaggedValue());
    ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
    while (!next->IsFalse()) {
        // ReturnIfAbrupt(next).
        RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, next.GetTaggedValue());
        // Let nextValue be IteratorValue(next).
        JSHandle<JSTaggedValue> nextValue(JSIterator::IteratorValue(thread, next));
        // ReturnIfAbrupt(nextValue).
        RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, next.GetTaggedValue());

        // If Type(nextItem) is not Object
        if (!nextValue->IsECMAObject()) {
            JSHandle<JSObject> typeError = factory->GetJSError(ErrorType::TYPE_ERROR, "nextItem is not Object");
            JSHandle<JSTaggedValue> record(
                factory->NewCompletionRecord(CompletionRecord::THROW, JSHandle<JSTaggedValue>(typeError)));
            JSTaggedValue ret = JSIterator::IteratorClose(thread, iter, record).GetTaggedValue();
            if (LIKELY(!thread->HasPendingException())) {
                THROW_NEW_ERROR_AND_RETURN_VALUE(thread, typeError.GetTaggedValue(), ret);
            };
            return ret;
        }
        // Let k be Get(nextItem, "0").
        JSHandle<JSTaggedValue> key = JSObject::GetProperty(thread, nextValue, keyIndex).GetValue();
        // If k is an abrupt completion, return IteratorClose(iter, k).
        if (UNLIKELY(thread->HasPendingException())) {
            return JSIterator::IteratorCloseAndReturn(thread, iter, key);
        }
        // Let v be Get(nextItem, "1").
        JSHandle<JSTaggedValue> value = JSObject::GetProperty(thread, nextValue, valueIndex).GetValue();
        // If v is an abrupt completion, return IteratorClose(iter, v).
        if (UNLIKELY(thread->HasPendingException())) {
            return JSIterator::IteratorCloseAndReturn(thread, iter, value);
        }
        // Let status be Call(adder, target, «nextValue.[[value]]»).
        auto info = NewRuntimeCallInfo(thread, adder, target, JSTaggedValue::Undefined(), 2U);
        info->SetCallArgs(key, value);  // 2: key and value pair
        JSTaggedValue ret = JSFunction::Call(info.Get());

        status.Update(ret);
        // If status is an abrupt completion, return IteratorClose(iter, status).
        if (UNLIKELY(thread->HasPendingException())) {
            return JSIterator::IteratorCloseAndReturn(thread, iter, status);
        }
        // Let next be IteratorStep(iter).
        next = JSIterator::IteratorStep(thread, iter);
    }
    return target.GetTaggedValue();
}
}  // namespace ark::ecmascript::base
